﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using Yunwei.Common;

namespace Yunwei.Web.Controllers
{
    public class AttachmentController : Controller
    {
        // GET: Attachment
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult CreateThumbnail(ThumbnailViewModel thumbnail)
        {
            string json = string.Empty;
            if (ModelState.IsValid)
            {
                if (thumbnail.Url.Contains(Request.Url.Authority))
                {
                    thumbnail.Url = PathUtil.UrlToRelativePath(thumbnail.Url, Request.Url.Authority);
                }
                else if (thumbnail.Url.Contains("http://") || thumbnail.Url.Contains(".com"))
                {
                    return Content("{\"error\":0,\"url\":\"" + thumbnail.Url + "\"}");
                }
                else
                {
                }

                string originPath = Request.MapPath(thumbnail.Url);
                string thumbnailPath = PathUtil.GetThumbnailPath(originPath);
                string tempPath = PathUtil.GetTempPath(originPath);

                bool sucess = Picture.CreateThumbnail(originPath, thumbnailPath, tempPath, (int)(thumbnail.Width + 0.5), (int)(thumbnail.Height + 0.5), thumbnail.Left + 0.5f, thumbnail.Top + 0.5f);
                if (sucess)
                {
                    string appRootDir = Request.MapPath(Request.ApplicationPath);//获取程序根目录
                    string url = WebConfigurationManager.AppSettings["serverDomain"] + "/" + PathUtil.PhysicPathToRelativePath(appRootDir, thumbnailPath);
                    url += "?t=" + DateTime.Now.Ticks;
                    json += "{\"error\":0,\"url\":\"" + url + "\"}";
                }
                else
                {
                    json += "{\"error\":500,\"msg\":\"生成缩略图失败\"}";
                }
            }

            return Content(json);
        }

        public ActionResult Upload(string dir)
        {
            string json = string.Empty;
            try
            {
                String userName = User.Identity.Name;
                if (string.IsNullOrEmpty(userName))
                {
                    return RedirectToAction("Login", "User", new { Area = "Admin" });
                }

                string rFolder = "upload/" + userName + "/" + DateTime.Now.ToString("yyyy-MM-dd");
                string pFolder = Request.MapPath("../" + rFolder);
                if (!System.IO.Directory.Exists(pFolder))
                {
                    System.IO.Directory.CreateDirectory(pFolder);
                }

                var hpFile = Request.Files[0];
                string fileName = DateTime.Now.Ticks + hpFile.FileName;
                hpFile.SaveAs(pFolder + "\\" + fileName);
                json = "{\"error\":0,\"url\":\"" + WebConfigurationManager.AppSettings["serverDomain"] + "/" + rFolder + "/" + fileName + "\"}";
            }
            catch (System.Web.HttpException ex)
            {
                json = "{\"error\":500,\"message\":\"上传失败，图片大小超过限制\"}";
            }
            catch (System.ArgumentOutOfRangeException ex)
            {
                json = "{\"error\":500,\"message\":\"上传失败，图片大小超过限制\"}";
            }
            catch (Exception ex)
            {
                json = "{\"error\":500,\"message\":\"上传失败\"}";
            }

            return Content(json);
        }

        [HttpGet]
        public ActionResult FileManager(string path, string order, string dir)
        {
            string json = string.Empty;
            if (ModelState.IsValid)
            {
                try
                {
                    String userName = User.Identity.Name;

                    if (string.IsNullOrEmpty(userName))
                    {
                        return RedirectToAction("Login", "User", new { Area = "Admin" });
                    }

                    path = Request["path"];
                    order = Request["order"];
                    dir = Request["dir"];

                    json += "{\"current_dir_path\":\"" + path + "\",\"current_url\":\"" + WebConfigurationManager.AppSettings["serverDomain"] + "/upload/" + userName + "/" + path + "\",\"moveup_dir_path\":\"\"";

                    if (string.IsNullOrEmpty(path))
                    {
                        string[] dirs = System.IO.Directory.GetDirectories(Request.MapPath("../upload/" + userName), "*", System.IO.SearchOption.TopDirectoryOnly);
                        json += ",\"total_count\":" + dirs.Length;
                        json += ",\"file_list\":[";
                        int i = 0;
                        foreach (string d in dirs)
                        {
                            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(d);
                            if (i > 0)
                                json += ",";
                            json += "{\"is_dir\":true,\"has_file\":true,\"filename\":\"" + di.Name + "\",\"filetype\":\"\",\"filesize\":0,\"datetime\":\"" + di.CreationTime.ToString("yyyy-MM-dd HH:mm:ss") + "\",\"is_photo\":false}";
                            i++;
                        }
                        json += "]}";
                    }
                    else
                    {
                        string[] files = System.IO.Directory.GetFiles(Request.MapPath("../upload/" + userName + "/" + path));

                        json += ",\"total_count\":" + files.Length;
                        json += ",\"file_list\":[";
                        int i = 0;
                        foreach (string d in files)
                        {
                            System.IO.FileInfo fi = new System.IO.FileInfo(d);
                            if (i > 0)
                                json += ",";
                            json += "{\"is_dir\":false,\"has_file\":false,\"dir_path\":\"\",\"filename\":\"" + fi.Name + "\",\"filetype\":\"" + fi.Extension + "\",\"filesize\":" + fi.Length + ",\"datetime\":\"" + fi.CreationTime.ToString("yyyy-MM-dd HH:mm:ss") + "\",\"is_photo\":true}";
                            i++;
                        }
                        json += "]}";
                    }

                }
                catch (Exception ex)
                {
                }
            }

            return Content(json);
        }
    }
}